// pages/doctor/doctor.js
Page({
  data: {
    // 当前选中的标签页
    activeTab: 'patients',
    
    // 标签页配置
    tabs: [
      { key: 'patients', name: '患者管理', icon: '👥' },
      { key: 'profile', name: '医生信息', icon: '👨‍⚕️' },
      { key: 'messages', name: '在线咨询', icon: '💬' }
    ],
    
    // 患者列表数据
    patients: [
      {
        id: 1,
        name: '张小明',
        age: 28,
        gender: '男',
        avatar: '/assets/images/avatar1.jpg',
        lastVisit: '2024-01-15',
        healthStatus: '良好',
        bmi: 22.5,
        bloodPressure: '120/80',
        bloodSugar: '5.8',
        dietHistory: [
          { date: '2024-01-15', meal: '早餐', food: '燕麦粥、鸡蛋、牛奶' },
          { date: '2024-01-15', meal: '午餐', food: '米饭、青菜、鱼肉' },
          { date: '2024-01-14', meal: '晚餐', food: '面条、蔬菜汤' }
        ],
        healthMetrics: {
          bmi: 22.5,
          bmiStatus: '正常',
          bodyFatRate: 18.5,
          bloodPressure: { systolic: 120, diastolic: 80 },
          bloodSugar: { fasting: 5.8, postprandial: 7.2 }
        }
      },
      {
        id: 2,
        name: '李小红',
        age: 35,
        gender: '女',
        avatar: '/assets/images/avatar2.jpg',
        lastVisit: '2024-01-14',
        healthStatus: '需关注',
        bmi: 26.8,
        bloodPressure: '135/85',
        bloodSugar: '6.5',
        dietHistory: [
          { date: '2024-01-14', meal: '早餐', food: '包子、豆浆' },
          { date: '2024-01-14', meal: '午餐', food: '米饭、红烧肉、青菜' },
          { date: '2024-01-13', meal: '晚餐', food: '粥、咸菜' }
        ],
        healthMetrics: {
          bmi: 26.8,
          bmiStatus: '偏胖',
          bodyFatRate: 28.5,
          bloodPressure: { systolic: 135, diastolic: 85 },
          bloodSugar: { fasting: 6.5, postprandial: 8.1 }
        }
      }
    ],
    
    // 医生个人信息
    doctorProfile: {
      name: '王医生',
      title: '主任医师',
      department: '营养科',
      hospital: '市人民医院',
      experience: '15年',
      specialties: ['糖尿病管理', '高血压饮食', '减重指导', '儿童营养'],
      education: '北京医科大学营养学博士',
      certifications: ['国家注册营养师', '糖尿病教育师'],
      introduction: '专注于慢性病营养管理，擅长糖尿病、高血压等疾病的饮食指导。',
      avatar: '/assets/images/doctor-avatar.jpg',
      phone: '138****8888',
      email: 'doctor@hospital.com'
    },
    
    // 消息列表
    messages: [
      {
        id: 1,
        patientId: 1,
        patientName: '张小明',
        patientAvatar: '/assets/images/avatar1.jpg',
        lastMessage: '医生，我最近血糖有点高，应该怎么调整饮食？',
        lastTime: '10:30',
        unreadCount: 2,
        status: 'active'
      },
      {
        id: 2,
        patientId: 2,
        patientName: '李小红',
        patientAvatar: '/assets/images/avatar2.jpg',
        lastMessage: '谢谢医生的建议，我会按照您说的去做',
        lastTime: '09:15',
        unreadCount: 0,
        status: 'active'
      }
    ],
    
    // 当前选中的患者
    selectedPatient: null,
    
    // 未读消息数量
    unreadCount: 0,
    
    // 编辑模式
    isEditingProfile: false,
    
    // 表单数据
    profileForm: {
      name: '',
      title: '',
      department: '',
      hospital: '',
      experience: '',
      specialties: [],
      education: '',
      certifications: [],
      introduction: '',
      phone: '',
      email: ''
    }
  },

  onLoad() {
    this.loadDoctorProfile();
  },

  onShow() {
    this.loadMessages();
  },

  // 加载医生档案
  loadDoctorProfile() {
    const profile = wx.getStorageSync('doctorProfile');
    if (profile) {
      this.setData({
        doctorProfile: profile,
        profileForm: { ...profile }
      });
    }
  },

  // 加载消息列表
  loadMessages() {
    // 这里可以从服务器获取消息列表
    // 暂时使用模拟数据
    this.calculateUnreadCount();
  },

  // 计算未读消息数量
  calculateUnreadCount() {
    const unreadCount = this.data.messages.filter(m => m.unreadCount > 0).length;
    this.setData({ unreadCount });
  },

  // 切换标签页
  switchTab(e) {
    const tab = e.currentTarget.dataset.tab;
    this.setData({ activeTab: tab });
  },

  // 查看患者详情
  viewPatientDetail(e) {
    const patientId = e.currentTarget.dataset.id;
    const patient = this.data.patients.find(p => p.id === patientId);
    this.setData({ selectedPatient: patient });
    
    wx.navigateTo({
      url: `/pages/doctor/patientDetail/patientDetail?id=${patientId}`
    });
  },

  // 编辑医生档案
  editProfile() {
    this.setData({ isEditingProfile: true });
  },

  // 保存医生档案
  saveProfile() {
    const { profileForm } = this.data;
    
    // 数据验证
    if (!profileForm.name || !profileForm.title || !profileForm.department) {
      wx.showToast({
        title: '请填写必要信息',
        icon: 'none'
      });
      return;
    }

    // 保存到本地存储
    wx.setStorageSync('doctorProfile', profileForm);
    
    this.setData({
      doctorProfile: profileForm,
      isEditingProfile: false
    });

    wx.showToast({
      title: '保存成功',
      icon: 'success'
    });
  },

  // 取消编辑
  cancelEdit() {
    this.setData({
      isEditingProfile: false,
      profileForm: { ...this.data.doctorProfile }
    });
  },

  // 输入处理
  onInputChange(e) {
    const { field } = e.currentTarget.dataset;
    const value = e.detail.value;
    this.setData({
      [`profileForm.${field}`]: value
    });
  },

  // 添加专长
  addSpecialty() {
    wx.showModal({
      title: '添加专长',
      editable: true,
      placeholderText: '请输入专长领域',
      success: (res) => {
        if (res.confirm && res.content) {
          const specialties = [...this.data.profileForm.specialties, res.content];
          this.setData({
            'profileForm.specialties': specialties
          });
        }
      }
    });
  },

  // 删除专长
  removeSpecialty(e) {
    const index = e.currentTarget.dataset.index;
    const specialties = this.data.profileForm.specialties;
    specialties.splice(index, 1);
    this.setData({
      'profileForm.specialties': specialties
    });
  },

  // 添加证书
  addCertification() {
    wx.showModal({
      title: '添加证书',
      editable: true,
      placeholderText: '请输入证书名称',
      success: (res) => {
        if (res.confirm && res.content) {
          const certifications = [...this.data.profileForm.certifications, res.content];
          this.setData({
            'profileForm.certifications': certifications
          });
        }
      }
    });
  },

  // 删除证书
  removeCertification(e) {
    const index = e.currentTarget.dataset.index;
    const certifications = this.data.profileForm.certifications;
    certifications.splice(index, 1);
    this.setData({
      'profileForm.certifications': certifications
    });
  },

  // 开始聊天
  startChat(e) {
    const patientId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/doctor/chat/chat?patientId=${patientId}`
    });
  },

  // 查看所有患者
  viewAllPatients() {
    wx.navigateTo({
      url: '/pages/doctor/patientList/patientList'
    });
  },

  // 添加新患者
  addPatient() {
    wx.navigateTo({
      url: '/pages/doctor/addPatient/addPatient'
    });
  }
})